package org.sg20.pagerank.pagerankiter;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.sg20.graphbuilder.GraphBuilderMapper;

import java.io.IOException;

public class PageRankIterReducer extends Reducer<Text, Text, Text, Text> {

    //后期记得对d进行设置
    public static final Double d = 0.85;

    /*
   map输出唐僧 |1.0|悟空,八戒  or   唐僧 pr
    */
    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        String links = "|";
        double pagerank = 0.0;
        for(Text value: values){
            String firSym = value.toString();
            if(firSym.startsWith("|")){
                links += firSym.substring(firSym.indexOf("|") + 1) ;
                continue;
            }
            String prContribution[] = firSym.split("\t");
            if(prContribution.length > 1)
                pagerank += Double.parseDouble(prContribution[1]);
        }
        //pagerank = (double)((1 - d)/ (double)(GraphBuilderMapper.getCharacterSize())) + d * pagerank;
        pagerank = 1 - d + d * pagerank;
        //格式为 pr|链接到的人物
        context.write(key, new Text(String.valueOf(pagerank) + links));

    }
}
